import pygame
from draw import *
from rock_kinds import *
from utils import *
from const import *
from random import randint
from pygame import mixer
from pathlib import Path

pygame.init()
pygame.display.set_caption('俄罗斯方块')
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

# BGM
mixer.init()
root_path = Path(__file__).parent.parent
mixer.music.load(root_path.joinpath('sounds/bgm.wav'))

speed = SPEED
rock_sz = ROCK_SZ
# 三面墙壁的坐标，为字典格式，key为y坐标，value为x坐标列表
wall_yx = draw_wall(screen, color = Color.gray1.value, wallRock_sz = rock_sz, height = HEIGHT)
# 沉底方块的坐标
frozen_rock_yx = dict()
print('yx:', wall_yx)

random_rock = dict(enumerate(NODE_KINDS))
kinds = len(NODE_KINDS)

score = 0
font = pygame.font.SysFont(None, 36)
text = font.render('score:', True, Color.white.value)
screen.blit(text, SCORESTR_POS)
# 分数文本显示颜色
score_color = Color.pink1.value
text = font.render('0', True, score_color)
screen.blit(text, SCORE_POS)

paused = False
gameover = False
start = False
new_record = False
levels = dict(enumerate(range(10, 170, 10)))
len_levels = len(levels)
level_index = 5

# 提示文本显示
prompt_text_display(screen)

# 难度等级文本显示颜色
level_color = Color.brown1.value
text = font.render(str(level_index), True, level_color)
screen.blit(text, LEVEL_TEXT4_POS)
# 历史最高成绩
best_record = 0
with open(root_path.joinpath('record.txt'), 'r') as f:
    records = [int(i[:-1]) for i in f.readlines()]
    if records:
        best_record = max(records)
        text = font.render(str(best_record), True, Color.white.value)
        screen.blit(text, RECORD_TEXT2_POS)
pygame.display.update()

# 开头设置
while not start:
    # 按上下箭头键设置难度，按空格键开始游戏
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                start = True
                mixer.music.play(loops = -1)
            elif event.key == pygame.K_UP:
                if level_index < len_levels - 1:
                    level_index += 1
                    # 难度等级文本显示
                    draw.rect(screen, BGCOLOR, pygame.Rect(LEVEL_TEXT4_POS[0], LEVEL_TEXT4_POS[1], rock_sz, rock_sz))
                    text = font.render(str(level_index), True, level_color)
                    screen.blit(text, LEVEL_TEXT4_POS)
                    pygame.display.update()
            elif event.key == pygame.K_DOWN:
                if level_index > 0:
                    level_index -= 1
                    # 难度等级文本显示
                    draw.rect(screen, BGCOLOR, pygame.Rect(LEVEL_TEXT4_POS[0], LEVEL_TEXT4_POS[1], rock_sz, rock_sz))
                    text = font.render(str(level_index), True, level_color)
                    screen.blit(text, LEVEL_TEXT4_POS)
                    pygame.display.update()

# 主程序
rock_kind = random_rock[randint(0, kinds - 1)]
while True:
    # mixer.music.pause()
    click_frames = levels[level_index]
    next_rock_kind = random_rock[randint(0, kinds - 1)]
    lr = len(rock_kind.val)
    lc = len(rock_kind.val[0])
    initx = (1 + (10 - lc) // 2) * rock_sz
    inity = -rock_sz * lr

    # 显示下一方块
    draw_russian_rock(screen = screen, x = NEXT_ROCK_POS[0], y = NEXT_ROCK_POS[1], rock_kind = next_rock_kind.val,
                      rock_sz = rock_sz,
                      color1 = Color.gray2.value)

    # 游戏结束判断条件
    if not movable(initx, inity, rock_kind.val, wall_yx, frozen_rock_yx):
        print('game over')
        gameover = True
        with open(root_path.joinpath('record.txt'), 'a') as f:
            f.write(str(score) + '\n')
        # 判断是否破纪录
        if score > best_record:
            new_record = True
            mixer.music.load(root_path.joinpath('sounds/new_record.mp3'))
            mixer.music.play()
        else:
            mixer.music.pause()
            # 音效
            mixer.Sound(root_path.joinpath('sounds/default.mp3')).play()

        print('历史记录：', records, best_record)

    imx1 = imy1 = 0
    imx2 = imy2 = 0
    while True:
        if paused and not gameover:
            imx1, imy1 = fancy_load_img(screen, imx1, imy1, root_path.joinpath('images/pause2.jpg'))

        if gameover:
            img_path = 'images/new_record.png' if new_record else 'images/finish.png'
            imx2, imy2 = fancy_load_img(screen, imx2, imy2, root_path.joinpath(img_path), rate = 4)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        imx2 = imy2 = 0

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            # 按键检测
            if event.type == pygame.KEYDOWN:
                # 暂停/继续aa
                if event.key == pygame.K_SPACE:
                    if not paused:
                        paused = True
                        mixer.music.pause()
                    else:
                        paused = False
                        mixer.music.unpause()

                if not paused:
                    # 旋转
                    if event.key == pygame.K_w and movable(initx, inity, rock_kind.next.val, wall_yx,
                                                           frozen_rock_yx):
                        # 音效
                        mixer.Sound(root_path.joinpath('sounds/rotate.wav')).play()
                        draw_russian_rock(screen = screen, x = initx, y = inity, rock_kind = rock_kind.val,
                                          rock_sz = rock_sz,
                                          color2 = BGCOLOR)
                        rock_kind = rock_kind.next
                        lr = len(rock_kind.val)
                    # 左移
                    elif event.key == pygame.K_a and movable(initx - rock_sz, inity, rock_kind.val, wall_yx,
                                                             frozen_rock_yx):
                        # 音效
                        mixer.Sound(root_path.joinpath('sounds/move.wav')).play()
                        draw_russian_rock(screen = screen, x = initx, y = inity, rock_kind = rock_kind.val,
                                          rock_sz = rock_sz,
                                          color2 = BGCOLOR)
                        initx -= rock_sz
                    # 右移
                    elif event.key == pygame.K_d and movable(initx + rock_sz, inity, rock_kind.val, wall_yx,
                                                             frozen_rock_yx):
                        # 音效
                        mixer.Sound(root_path.joinpath('sounds/move.wav')).play()
                        draw_russian_rock(screen = screen, x = initx, y = inity, rock_kind = rock_kind.val,
                                          rock_sz = rock_sz,
                                          color2 = BGCOLOR)
                        initx += rock_sz
                    # 加速
                    elif event.key == pygame.K_s:
                        click_frames += 10

        if not paused and not gameover:
            draw.rect(screen, BGCOLOR, pygame.Rect(rock_sz, 0, 10 * rock_sz, HEIGHT - rock_sz))
            draw_russian_rock(screen = screen, x = initx, y = inity, rock_kind = rock_kind.val, rock_sz = rock_sz,
                              color2 = BGCOLOR)
            if movable(initx, inity + speed, rock_kind.val, wall_yx, frozen_rock_yx):
                inity += speed
            else:
                print('freeze')
                frozen_rock_yx = freeze_rock(initx, inity, rock_kind.val, frozen_rock_yx)
                # 消行
                full_lines = []
                for k, v in frozen_rock_yx.items():
                    if len(v) == 10:
                        full_lines.append((k, v))
                if full_lines:
                    # 音效
                    mixer.Sound(root_path.joinpath('sounds/remove_lines.mp3')).play()

                    score += 2 ** len(full_lines)
                    # score显示
                    draw.rect(screen, BGCOLOR, pygame.Rect(SCORE_POS[0], SCORE_POS[1], rock_sz * 3, rock_sz))
                    text = font.render(str(score), True, score_color)
                    screen.blit(text, SCORE_POS)
                    print('score:', score)
                    full_lines = sorted(full_lines, key = lambda x: x[0])[::-1]
                    frozen_rock_yx = remove_lines(frozen_rock_yx, full_lines)
                else:
                    # 音效
                    mixer.Sound(root_path.joinpath('sounds/down.mp3')).play()
                print('yx:', frozen_rock_yx)
                break
            # prompt_text_load(screen)
            draw_russian_rock(screen = screen, x = initx, y = inity, rock_kind = rock_kind.val, rock_sz = rock_sz,
                              color1 = Color.blue2.value)
            for y, v in frozen_rock_yx.items():
                for x in v:
                    draw_rock(sc = screen, x = x, y = y, size = rock_sz, fillcolor = Color.gray2.value)

            draw_wall(screen, color = Color.gray1.value, wallRock_sz = rock_sz, height = HEIGHT)
            pygame.display.update()

        clock.tick(click_frames)

    rock_kind = next_rock_kind
    draw_russian_rock(screen = screen, x = NEXT_ROCK_POS[0], y = NEXT_ROCK_POS[1], rock_kind = next_rock_kind.val,
                      rock_sz = rock_sz, color1 = BGCOLOR, color2 = BGCOLOR)
